package com.dex4d.ui.qr.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.dex4d.BuildConfig;
import com.dex4d.R;
import com.dex4d.core.http.DefaultTransformer;
import com.dex4d.core.http.JsonApiWrapper;
import com.dex4d.core.subscribers.ProgressSubscriber;
import com.dex4d.model.User;
import com.dex4d.ui.qr.EasyDoneActivity;
import com.dex4d.ui.qr.model.QRRequest;
import com.dex4d.ui.qr.model.QRResult;
import com.dex4d.ui.qr.utils.AddressUtils;
import com.dex4d.ui.qr.utils.TipUtils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.functions.Func1;


public class EasyLoginAuthFragment extends Fragment {

    private static final String ARG_PARAM1 = "url";

    @BindView(R.id.txt_show_address)
    TextView txt_show_address;

    @BindView(R.id.txt_show_time)
    TextView txt_show_time;

    @BindView(R.id.btn_confirm)
    Button btn_confirm;

    @BindView(R.id.btn_reject)
    Button btn_reject;


    private String mParamUrl;


    public EasyLoginAuthFragment() {
        // Required empty public constructor
    }


    public static EasyLoginAuthFragment newInstance(String param1) {
        EasyLoginAuthFragment fragment = new EasyLoginAuthFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            //动态修改URL ，此处拼接完成
            mParamUrl = BuildConfig.QR_URL_API + getArguments().getString(ARG_PARAM1);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_easy_login_auth, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        txt_show_address.setText(AddressUtils.convertAddress(User.getInstance().getAddress()));
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
        String time = formatter.format(Calendar.getInstance().getTime());
        txt_show_time.setText(time);

        mParamUrl = mParamUrl.concat("&address=").concat(User.getInstance().getAddress());

        JsonApiWrapper
                .serviceApi()
                .QRLogin(mParamUrl)
                .compose(new DefaultTransformer<QRResult>())
                .subscribe(new ProgressSubscriber<QRResult>(getActivity(), true) {
                    @Override
                    public void onNext(QRResult result) {
                        if (!result.isOk()) {//失败
                            TipUtils.showTips(getActivity(), result);
                        }
                    }
                });
    }


    @OnClick(R.id.btn_confirm)
    public void confirmClick() {
        login(true);
    }

    @OnClick(R.id.btn_reject)
    public void rejectClick() {
        login(false);
    }

    public void login(final boolean isLogin) {
        JsonApiWrapper
                .serviceApi()
                .QRLogin(mParamUrl)
                .flatMap(new Func1<QRResult, Observable<QRResult>>() {
                    @Override
                    public Observable<QRResult> call(QRResult result) {
                        QRRequest request = QRRequest.createLoginRequest(mParamUrl, isLogin);
                        return JsonApiWrapper.serviceApi().QRLoginConfirm(BuildConfig.QR_URL_API + "/qrconfirm", request);
                    }
                })
                .compose(new DefaultTransformer<QRResult>())
                .subscribe(new ProgressSubscriber<QRResult>(getActivity(), true) {
                    @Override
                    public void onNext(QRResult result) {
                        if (isLogin) {
                            if (result.isOk()) {//成功
                                EasyDoneActivity.start(getActivity(), mParamUrl);
                                getActivity().finish();
                            } else {//失败
                                TipUtils.showTips(getActivity(), result);
                            }
                        } else {
                            getActivity().finish();
                        }
                    }
                });

    }

}
